package factory

import (
	"apibe/grpc/rome/v1/share/crypt"
	"apibe/grpc/rome/v1/share/db"
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"time"
)

type LoggerLevel string

const (
	Info   LoggerLevel = "Info"
	Waring LoggerLevel = "Waring"
	Err    LoggerLevel = "Err"
	Panic  LoggerLevel = "Panic"
)

// logger
// 日志 分类、人物、时间、ip、做了什么事情
type logger struct {
	ID          primitive.ObjectID `json:"_id" bson:"_id"`
	EventID     interface{}        `json:"event_id" bson:"event_id"`
	LoggerType  string      `json:"type" bson:"type"`
	LoggerLevel LoggerLevel `json:"level" bson:"level"`
	Name        string      `json:"name" bson:"name"`
	Time        time.Time          `json:"time" bson:"time"`
	IP          string             `json:"ip" bson:"ip"`
	Description string             `json:"description" bson:"description"`
}

// OperationLogger
// 创建一个新的平台操作日志
func OperationLogger(level LoggerLevel, EventID interface{}, claims *crypt.CustomClaims, description string) {
	l := logger{
		ID:          primitive.NewObjectID(),
		LoggerType:  "operation",
		LoggerLevel: level,
		EventID:     EventID,
		Name:        claims.UserName,
		Time:        time.Now(),
		IP:          claims.Ip,
		Description: description,
	}
	l.insert(db.CollectionLogger)
}

// ActionLogger
// 创建一个用户行为日志
func ActionLogger(level LoggerLevel, EventID interface{}, claims *crypt.CustomClaims, description string) {
	l := logger{
		ID:          primitive.NewObjectID(),
		LoggerLevel: level,
		LoggerType:  "action",
		EventID:     EventID,
		Name:        claims.UserName,
		Time:        time.Now(),
		IP:          claims.Ip,
		Description: description,
	}
	l.insert(db.CollectionLogger)
}

func OperationLoggerFindManyIds(id interface{}) (*[]logger, error) {
	var ls []logger
	ctx := context.Background()
	filter := bson.M{"event_id": id}
	find, err := db.GetMongoCollection(db.CollectionLogger).Find(ctx, filter)
	if err != nil {
		return nil, err
	}
	err = find.All(ctx, &ls)
	return &ls, err
}

func ActionLoggerFindManyIds(id interface{}) (*[]logger, error) {
	var ls []logger
	ctx := context.Background()
	filter := bson.M{"event_id": id}
	find, err := db.GetMongoCollection(db.CollectionLogger).Find(ctx, filter)
	if err != nil {
		return nil, err
	}
	err = find.All(ctx, &ls)
	return &ls, err
}

func (l *logger) insert(collection string) {
	ctx := context.Background()
	_, _ = db.GetMongoCollection(collection).InsertOne(ctx, l)
}
